using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using EnvDTE;

namespace Skim.Ssms.AddIn.ActiveFileExplorer
{
    internal static class DocumentTypeFilter
    {
        public static IEnumerable<Document> FilterQueryDocuments(IEnumerable<Document> documents)
        {
            return documents.WhereOpenDocument(IsQueryDocument);
        }

        public static IEnumerable<Document> FilterDesignDocuments(IEnumerable<Document> documents)
        {
            return documents.WhereOpenDocument(IsDesignerDocument);
        }

        public static IEnumerable<Document> FilterSolutionDocuments(IEnumerable<Document> documents)
        {
            return documents.WhereOpenDocument(IsSolutionDocument);
        }

        private static IEnumerable<Document> WhereOpenDocument(
            this IEnumerable<Document> documents, Func<Document, bool> filter)
        {
            return from document in FilterOpenDocuments(documents)
                   where filter(document)
                   select document;
        }

        /// <summary>
        /// Filter and return only open documents
        /// </summary>
        /// <remarks>
        /// Documents that are being closed have ActiveWindow set to null
        /// </remarks>
        public static IEnumerable<Document> FilterOpenDocuments(IEnumerable<Document> documents)
        {
            return from document in documents
                   where document.ActiveWindow != null
                   select document;
        }
        
        public static IEnumerable<Document> FilterOpenDocuments(Documents documents)
        {
            return FilterOpenDocuments(documents.Cast<Document>());
        }

        public static bool IsQueryDocument(Document document)
        {
            return document.ProjectItem != null;
        }

        public static bool IsSolutionDocument(Document document)
        {
            return document.ProjectItem == null
                   && !IsDesignerDocument(document);
        }

        public static bool IsDesignerDocument(Document document)
        {
            // HACK: Designer document's full name contains server, database, schema and table information
            //const string pattern = @"^Server\[[^\]]*\]/Database\[@Name='(?<Database>[^']*)'\]/Table\[@Name='(?<Table>[^']*)' and @Schema='(?<Schema>[^']*)'\]$";
            const string pattern = @"^Server\[[^\]]*\]/Database\[@Name='(?<Database>[^']*)'\]";
            return document.ProjectItem == null
                   && Regex.IsMatch(document.FullName, pattern);
        }
    }
}